//
//  DetailViewController.m
//  album
//
//  Created by 云天 李 on 12-1-18.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DetailViewController.h"
#import "Album.h"
#import "Picture.h"
#import "AlbumDB.h"
#import "AlbumPictureViewController.h"
#import "AlbumHelper.h"

@implementation DetailViewController

@synthesize currentAlbum = _currentAlbum;
@synthesize thumbnailTableView = _thumbnailTableView;
@synthesize pictures = _pictures;
@synthesize toolbar = _toolbar;
@synthesize imagePickerController = _imagePickerController;
@synthesize pickedImage = _pickedImage;
@synthesize albumPictureViewController = _albumPictureViewController;

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    // 进入编辑状态时，后退按钮不可见
    self.navigationItem.hidesBackButton = editing;
    
    // 隐藏或者显示工具栏
    self.toolbar.hidden = !editing;
    
    CGRect f = self.thumbnailTableView.frame;
    float h = 0.0f;
    if(editing)
    {
         h = f.size.height - 44.0f;
    }
    else
    {
         h = f.size.height + 44.0f;
    }
    self.thumbnailTableView.frame = CGRectMake(f.origin.x, f.origin.y, f.size.width, h);
    
    [super setEditing:editing animated:animated];
}

// 从系统照片复制图片
- (IBAction)copyPicture:(id)sender
{
    // 从系统照片库中获取图片
    if (self.imagePickerController == nil)
    {
        self.imagePickerController = [[[UIImagePickerController alloc] init] autorelease];
        self.imagePickerController.delegate = self;
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    
    [self presentModalViewController:self.imagePickerController animated:YES];
}

// 处理系统照片中复制的图片
- (void)processPickedImage: (UIImage *) image
{
	NSLog(@"%@", image);
	
    NSString *pictureName = [AlbumHelper createRandomPictureName];
    
    // 正常图片
    NSString *name = [AlbumHelper pictureFilePath:pictureName withAlbum:self.currentAlbum.albumid];
    [AlbumHelper savePictureData:UIImageJPEGRepresentation(image, 1.0f) withName:name];
    
    NSError *error;
    NSDictionary *attrib = [[NSFileManager defaultManager] attributesOfItemAtPath:name error:&error];
    
    // 缩略图文件名后有个"-tn"
    NSString *thumbnailName = [NSString stringWithFormat:@"%@-tn", pictureName];
    name = [AlbumHelper pictureFilePath:thumbnailName withAlbum:self.currentAlbum.albumid];
    UIImage *thumbnail = [AlbumHelper createThumbnail:image];
    [AlbumHelper savePictureData:UIImageJPEGRepresentation(thumbnail, 1.0f) withName:name];
    
    // 写到数据库
    Picture *picture = [[Picture alloc] init];
    picture.picturename = pictureName;
    picture.albumid = self.currentAlbum.albumid;
    picture.width = image.size.width;
    picture.height = image.size.height;
    picture.size = [attrib fileSize];
    
    [AlbumDB savePictureToAlbum:picture];
    [picture release];

    [self loadPictures];
    [self.thumbnailTableView reloadData];
}

// 从数据库读取当前相册下的所有图片
- (void) loadPictures
{
    if (self.pictures == nil)
    {
        self.pictures = [NSMutableArray array];
    }
    else
    {
        [self.pictures removeAllObjects];
    }
    
    self.pictures = [AlbumDB fetchPictures:self.currentAlbum.albumid];
}

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

// this get called when an image has been chosen from the library or taken from the camera
//
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self processPickedImage: [info valueForKey:UIImagePickerControllerOriginalImage]];
    
    [self dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - init
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.navigationItem.rightBarButtonItem = self.editButtonItem;
    }
    return self;
}


- (void)dealloc
{
    [_currentAlbum release];
    [_thumbnailTableView release];
    [_pictures release];
    [_toolbar release];
    [_pickedImage release];
    [_imagePickerController release];
    [_albumPictureViewController release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = self.currentAlbum.title;
    
    // 添加工具栏按钮
    UIBarButtonItem *copyButtonitem = [[UIBarButtonItem alloc]  
                                       initWithTitle:@"从系统照片库复制图片" 
                                       style:UIBarButtonItemStyleBordered 
                                       target:self   
                                       action:@selector(copyPicture:)
                                       ]; 
    NSArray *items = [NSArray arrayWithObjects: copyButtonitem, nil];
    
    [self.toolbar setItems:items animated:NO];
    [copyButtonitem release];
    
    // 读取数据库中的图片记录到一个数组
    [self loadPictures];
}

- (void)viewWillAppear:(BOOL)animated
{
	// 显示UINavigationController默认工具栏
	[self.navigationController setToolbarHidden:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - UITableViewDataSource
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.pictures count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    Picture *_picture = [self.pictures objectAtIndex:[indexPath row]];
    
    NSString *thumbnailName = [AlbumHelper pictureFilePath:[NSString stringWithFormat:@"%@-tn", _picture.picturename] withAlbum:self.currentAlbum.albumid];
    cell.imageView.image = [UIImage imageWithContentsOfFile:thumbnailName];
    
    cell.textLabel.text = [NSString stringWithFormat:@"宽: %i, 高: %i", _picture.width, _picture.width];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"大小: %iKB", _picture.size / 1024];

    return cell;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 1、从数据库中移除记录
        Picture *_picture = [self.pictures objectAtIndex:[indexPath row]];
        [AlbumDB deletePicture:_picture];
        // 2、移除iPhone内的图片及缩略图
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        NSError *error;
        NSString *pictureName = [AlbumHelper pictureFilePath:[NSString stringWithFormat:@"%@", _picture.picturename] withAlbum:self.currentAlbum.albumid];
        [fileManager removeItemAtPath:pictureName error:&error];
        NSString *thumbnailName = [AlbumHelper pictureFilePath:[NSString stringWithFormat:@"%@-tn", _picture.picturename] withAlbum:self.currentAlbum.albumid];
        [fileManager removeItemAtPath:thumbnailName error:&error];
        // 3、从数组中移除记录
        [self.pictures removeObject:_picture];
        

        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!self.albumPictureViewController) {
        self.albumPictureViewController = [[[AlbumPictureViewController alloc] initWithNibName:@"AlbumPictureViewController" bundle:nil] autorelease];
    }
    
    [self.albumPictureViewController setCurrentPicture:[self.pictures objectAtIndex:[indexPath row]]];
    [self.albumPictureViewController setCurrentPage:[indexPath row] + 1];
    [self.albumPictureViewController.scrollView setScrollEnabled:NO];
    
    [self.navigationController pushViewController:self.albumPictureViewController animated:YES];
    [self.albumPictureViewController.scrollView setScrollEnabled:YES];
}

// 设置表格的行高
- (CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return kThumbnailDimension;
}
@end
